package com.tudouji.project.permission.service.impl;

import java.util.*;

import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.project.handover.domain.CustomerVo;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.service.IDepartmentService;
import com.tudouji.project.permission.domain.FlowPermissionAssignDO;
import com.tudouji.project.permission.domain.Permissiondef;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.service.IStoreroomService;
import com.tudouji.project.system.domain.SysDept;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.mapper.SysUserMapper;
import com.tudouji.project.system.service.ISysDeptService;
import com.tudouji.project.system.service.ISysUserService;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tudouji.project.permission.mapper.SalespermissionMapper;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.ISalespermissionService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * ����ϵͳȨ��Service业务层处理
 * 
 * @author tudouji
 * @date 2021-04-23
 */
@Service
public class SalespermissionServiceImpl implements ISalespermissionService 
{
    @Autowired
    private SalespermissionMapper salespermissionMapper;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IStoreroomService storeroomService;
    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 查询����ϵͳȨ��
     * 
     * @param guid ����ϵͳȨ��ID
     * @return ����ϵͳȨ��
     */
    @Override
    public Salespermission selectSalespermissionById(String guid)
    {
        return salespermissionMapper.selectSalespermissionById(guid);
    }

    /**
     * 查询����ϵͳȨ��列表
     * 
     * @param salespermission ����ϵͳȨ��
     * @return ����ϵͳȨ��
     */
    @Override
    public List<Salespermission> selectSalespermissionList(Salespermission salespermission)
    {
        return salespermissionMapper.selectSalespermissionList(salespermission);
    }

    /**
     * 新增����ϵͳȨ��
     * 
     * @param salespermission ����ϵͳȨ��
     * @return 结果
     */
    @Override
    public int insertSalespermission(Salespermission salespermission)
    {
        //salespermission中添加user_id,
        SysUser sysUser = sysUserService.selectUserById(salespermission.getUserId());
        if (null != salespermission.getDeptId()){
            SysDept sysDept = sysDeptService.selectDeptById(salespermission.getDeptId());
            salespermission.setDepartid(sysDept.getGuid());

        }
        salespermission.setUserguid(sysUser.getGuid());
        for(Permissiondef per : salespermission.getPermissions()){
            salespermission.setGuid(IdUtils.fastSimpleUUID());
            salespermission.setCreatetime(DateUtils.getNowDate());
            salespermission.setLastupdate(DateUtils.getNowDate());
            salespermission.setPermission(per.getCode());
            salespermission.setOperatorid(SecurityUtils.getLoginUser().getUser().getUserId().toString());
            salespermission.setStatus(1);
            salespermissionMapper.insertSalespermission(salespermission);
        }
        return 1;
    }

    /**
     * 修改����ϵͳȨ��
     * 
     * @param salespermission ����ϵͳȨ��
     * @return 结果
     */
    @Override
    public int updateSalespermission(Salespermission salespermission)
    {
        if (StringUtils.isNotBlank(salespermission.getDepartid())){
            salespermission.setDeptId(Long.valueOf(salespermission.getDepartid()));
            salespermission.setDepartid(null);
        }

        return salespermissionMapper.updateSalespermission(salespermission);
    }

    /**
     * 批量删除����ϵͳȨ��
     * 
     * @param guids 需要删除的����ϵͳȨ��ID
     * @return 结果
     */
    @Override
    public int deleteSalespermissionByIds(String[] guids)
    {
        return salespermissionMapper.deleteSalespermissionByIds(guids);
    }

    /**
     * 删除����ϵͳȨ��信息
     * 
     * @param guid ����ϵͳȨ��ID
     * @return 结果
     */
    @Override
    public int deleteSalespermissionById(String guid)
    {
        return salespermissionMapper.deleteSalespermissionById(guid);
    }

    @Override
    public List<Salespermission> getPermByScAndFunc(String userid, String functionType, String scopeType) {
        if (null == userid){
            return new ArrayList<Salespermission>();
        }
        Salespermission permission = new Salespermission();
        permission.setOpttype(functionType);
        permission.setUserguid(userid);
        permission.setScopeType(scopeType);
        List<Salespermission> permissions = salespermissionMapper.findSrDeps(permission);
        return permissions;
    }
    @Override
    public List<Salespermission> getPermByScAndFuncSYS(Long userid, String functionType, String scopeType) {
        if (null == userid){
            return new ArrayList<Salespermission>();
        }
        Salespermission permission = new Salespermission();
        permission.setOpttype(functionType);
        permission.setUserId(userid);
        permission.setScopeType(scopeType);
        List<Salespermission> permissions = salespermissionMapper.findSrDeps(permission);
        return permissions;
    }
    @Override
    public List<Department> getDepsPermisByOrg(Salespermission per){
        List<Department> permissions = salespermissionMapper.getDepsPermisByOrg(per);
        return permissions;
    }

    @Override
    public List<Department> getPermssionForDepart(String tuserId, String functionTypes, String departype) throws Exception{
        boolean isPermission4 = false;
        List<Department> result = new ArrayList<>();
        if (null == tuserId) {
            return result;
        }
        Salespermission p = new Salespermission();
        p.setUserguid(tuserId);
        p.setOpttype(functionTypes);
        List<Salespermission> permissions = salespermissionMapper.findPCPerms(p);

        if (permissions.size() == 0) {
            return result;
        }
        for (Salespermission permission : permissions) {
            //判断该用户是否有全局权限
            if (permission.getPermss().getScopetype() == 4) {
                isPermission4 = true;
                break;
            }
        }

        //如果有全局权限，则加载所有部门，库房
        if (isPermission4) {
            Department department = new Department();
            department.setType(Integer.valueOf(departype));
            department.setStatus(1);
            return departmentService.selectDepartmentList(department);
        } else {
            Salespermission salespermission = new Salespermission();
            salespermission.setUserguid(tuserId);
            salespermission.setOpttype(functionTypes);
            salespermission.setDepartype(departype);
            return salespermissionMapper.findPCPermDepartment(salespermission);
        }
    }
    @Override
    public List<Storeroom> getPermssionForSr(String tuserId, String functionTypes){
        boolean isPermission4 = false;
        List<Storeroom> result = new ArrayList<>();
        if (null == tuserId) {
            return null;
        }
        Salespermission p = new Salespermission();
        p.setUserguid(tuserId);
        p.setOpttype(functionTypes);
        List<Salespermission> permissions = salespermissionMapper.findPCPerms(p);

        if (permissions.size() == 0) {
            return null;
        }
        for (Salespermission permission : permissions) {
            //判断该用户是否有全局权限
            if (permission.getPermss().getScopetype() == 4) {
                isPermission4 = true;
                break;
            }
        }

        //如果有全局权限，则加载所有部门，库房
        if (isPermission4) {
            return result;
        } else {
            Salespermission salespermission = new Salespermission();
            salespermission.setUserguid(tuserId);
            salespermission.setOpttype(functionTypes);
            return salespermissionMapper.findPCPermStoreroom(salespermission);
        }
    }


    @Override
    public List<SysDept> getDepsByPermissionCode(Integer code, String deptStats) {

        Long  userId = SecurityUtils.getLoginUser().getUser().getUserId();
        FlowPermissionAssignDO per=new FlowPermissionAssignDO();
        per.setUserId(userId);
        per.setPermission(code);
        if (StringUtils.isNotBlank(deptStats)) {
            String[] sts = deptStats.split(",");
            Integer[] s = (Integer[]) ConvertUtils.convert(sts, Integer.class);

            per.setStats(s);
        }
        return salespermissionMapper.getDepsByPermissionCode(per);
    }

    @Override
    public AjaxResult getPermis(Integer id) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Integer[] permis = new Integer[0];
        Salespermission per = new Salespermission();
        per.setUserId(sysUser.getUserId());
        per.setPermission(id);
        List<Salespermission> permissions = salespermissionMapper.selectSalespermissionList(per);
       /* if (permissions.size() > 0) {
            Integer[] perms = new Integer[permissions.size()];
            for (int i = 0; i < permissions.size(); i++) {
                perms[i] = permissions.get(i).getPermission();
            }
            List li = Arrays.asList(perms);
            Set set = new HashSet(li);
            permis = (Integer[]) set.toArray(new Integer[0]);
        }
        return AjaxResult.success(permis);*/
        return AjaxResult.success(permissions);
    }

    @Override
    public List<Storeroom> getUserOfSrbyPermssion(Storeroom storeroom) {
        return salespermissionMapper.getUserOfSrbyPermssion(storeroom);
    }

    public List<Salespermission> getPermBySrOrDepart(Long userId, String functionType, String scopeType, String srguid
            , String departid) {
        Salespermission permission = new Salespermission();
        permission.setOpttype(functionType);
        permission.setUserId(userId);
        permission.setScopeType(scopeType);
        permission.setSrguid(srguid);
        permission.setDepartid(departid);
        List<Salespermission> permissions = salespermissionMapper.findSrDeps(permission);
        return permissions;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult usertransfer(String transferType, Long userId, Long usertransferId, Long permission) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        SysUser user = sysUserService.selectUserById(userId);

        if(null != userId || null != usertransferId){
            return AjaxResult.error("源用户或目标用户未选中！");
        }
        if(userId.longValue() == usertransferId.longValue()){
            return AjaxResult.error("源用户与目标用户不能为同一人！");
        }

        Salespermission sp = new Salespermission();
        sp.setUserId(usertransferId);
        if (null != permission){
            sp.setId(permission);
        }
        //根据权限code查询权限列表
        List<Salespermission> sps = this.selectSalespermissionList(sp);

        for (Salespermission per : sps){
            Salespermission findSale = new Salespermission();
            findSale.setUserId(sysUser.getUserId());
            findSale.setPermission(per.getPermission());
            findSale.setType(per.getType());
            findSale.setSrguid(per.getSrguid());
            findSale.setDepartid(per.getDepartid());
            findSale.setDeptId(per.getDeptId());
            findSale = salespermissionMapper.selectSalespermission(findSale);
            if (null == findSale){
                if (org.apache.commons.lang3.StringUtils.equals(transferType, "copy")) {  //权限复制
                    per.setUserguid(user.getTuserId());
                    per.setUserId(user.getUserId());
                    per.setOperatorid(sysUser.getTuserId());
                    salespermissionMapper.insertSalespermission(per);
                } else { //权限移交
                    per.setUserguid(user.getTuserId());
                    per.setUserId(user.getUserId());
                    salespermissionMapper.updateSalespermission(per);
                }
            }else{
                if (org.apache.commons.lang3.StringUtils.equals(transferType, "copy")) {  //权限复制

                } else { //权限移交
                    salespermissionMapper.deleteSalespermissionById(per.getGuid());
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     *权限移交
     * @param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult trans(Long fromUserId,Long toUserId,String picked) {
//        创建人
        SysUser user= SecurityUtils.getLoginUser().getUser();
//        交出人
        SysUser fromUser=sysUserMapper.selectUserById(fromUserId);
//        接受人
        SysUser toUser=sysUserMapper.selectUserById(toUserId);

        Salespermission salespermission=new Salespermission();
        salespermission.setUserguid(fromUser.getGuid());

        //根据交接人guid查询权限列表
        List<Salespermission> salespermissionList=salespermissionMapper.selectSalespermissionList(salespermission);

            String userguid=toUser.getGuid();
            for (Salespermission sale:salespermissionList){
                Integer permission=sale.getPermission();
                Long deptId=null;
                String srguid=null;
                String orgid=null;
                List<Salespermission> toUserPermlist;
                //判断接收人是否存在要移交的权限
                //1组织   2部门   3库房+部门    4全局    5其他   6销售+部门    7库房
                switch (sale.getScopeType()) {
                    case "1": {
                        orgid=sale.getOrgid();
                        break;
                    }
                    case "6":
                    case "2": {
                        deptId = sale.getDeptId();
                        break;
                    }
                    case "3": {
                        deptId = sale.getDeptId();
                        srguid=sale.getSrguid();
                        break;
                    }
                    case "4": {
                        break;
                    }
                    case "7": {
                        srguid=sale.getSrguid();
                        break;
                    }
                    default:
                        return AjaxResult.error("权限类型错误");
                }
                toUserPermlist = salespermissionMapper.selectPermissionByUserid(userguid,permission,deptId,srguid,orgid);
                if (toUserPermlist.isEmpty()) {
                    sale.setUserId(toUser.getUserId());
                    sale.setUserguid(toUser.getGuid());
                    if(picked.equals("1")) {
                        sale.setGuid(IdUtils.fastSimpleUUID());
                        salespermissionMapper.insertSalespermission(sale);
                    }else {
                        salespermissionMapper.updateSalespermission(sale);
                    }
                }
            }
        return AjaxResult.success();
    }

    /**
     * 根据用户id查询用户权限
     * @param guid
     * @param permission
     * @return
     */
    @Override
    public List<Salespermission> selectPermissionByUserid(String guid,Integer permission,Long deptId,String srguid,String orgid){
        return salespermissionMapper.selectPermissionByUserid(guid, permission,deptId,srguid,orgid);
    }
}
